<template>
  <el-dialog
    v-model="visible"
    title="上传发票"
    :close-on-click-modal="false"
    width="800px"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="auto"
    >
      <el-form-item
        label="发票抬头："
        style="margin-left: 20px"
      >
        <span class="inv-item">
          {{ dataForm.headerName }}
          <span class="copy">
            <hm-copy :text="dataForm.headerName" />
          </span>
        </span>
      </el-form-item>

      <el-form-item
        label="税号："
        style="margin-left: 20px"
      >
        <span class="inv-item">
          {{ dataForm.invoiceTaxNumber }}
          <span class="copy">
            <hm-copy :text="dataForm.invoiceTaxNumber" />
          </span>
        </span>
      </el-form-item>

      <el-form-item
        label="物料清单："
        style="margin-left: 20px"
      >
        <div
          class="default-btn text-btn"
          @click="onDownload"
        >
          下载
        </div>
      </el-form-item>

      <el-form-item
        label="发票："
        prop="fileId"
        style="margin-left: 20px"
      >
        <div class="upload-video-box">
          <div
            v-for="(item, index) in docList"
            :key="index"
            class="video-preview"
          >
            <div class="avatar-uploader-popup">
              <doc-icon
                type="pdf"
                :width="100"
              />
              <el-icon
                class="el-icon-delete"
                style="color: red"
                @click="preDeleteVideo(index)"
              >
                <Delete />
              </el-icon>
            </div>

            <!-- 显示上传进度 -->
            <div
              v-show="isSubmit"
              class="progress"
            >
              <el-progress
                type="circle"
                :width="80"
                :percentage="item.progress || 0"
              />
            </div>
          </div>
        </div>
        <el-upload
          v-show="docList.length == 0"
          ref="uploadRef"
          v-model:file-list="docList"
          name="excelFile"
          class="upload-img-preview"
          list-type="picture-card"
          action=""
          :multiple="false"
          :auto-upload="false"
          :show-file-list="false"
          :limit="1"
          :http-request="httpRequest"
          :on-change="onUploadChange"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <div>
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])

const dataFormRef = ref(null)
const visible = ref(false)
const isSubmit = ref(false)
const dataForm = ref({})
const dataRule = {
  fileId: [
    { required: true, message: '发票不能为空', trigger: 'blur' }
  ]
}

let shopId = ''
const orderNumber = ref('')
const init = (order) => {
  shopId = order.shopId
  orderNumber.value = order.orderNumber
  docList.value = []
  visible.value = true
  dataFormRef.value?.resetFields()
  http({
    url: http.adornUrl('/orderInvoice/page'),
    method: 'get',
    params: http.adornParams({
      shopId,
      orderNumber: orderNumber.value,
      size: 10,
      current: 1
    })
  }).then(({ data }) => {
    const _data = data.records[0] || {}
    dataForm.value = _data
    docList.value = _data.fileId ? [
      {
        filePath: _data.fileId
      }
    ] : []
  })
}
defineExpose({ init })

const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (isSubmit.value) {
        return false
      }
      // 判断是否是新上传的文件
      const { status, filePath } = docList.value[0]
      if (status == 'success' && filePath) {
        onSave()
        return
      }
      isSubmit.value = true
      uploadRef.value?.submit()
    }
  })
}

const onSave = () => {
  http({
    url: http.adornUrl('/orderInvoice'),
    method: 'put',
    data: http.adornData({
      orderInvoiceId: dataForm.value.orderInvoiceId,
      fileId: dataForm.value.fileId
    })
  }).then(() => {
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1000,
      onClose: () => {
        isSubmit.value = false
        visible.value = false
        emit('refreshDataList')
      }
    })
  }).catch((e) => {
    isSubmit.value = false
    // docList.value = []
  })
}

const docList = ref([])
const uploadRef = ref(null)
const httpRequest = (event) => {
  docList.value.forEach(item => {
    if (item.uid === event.file.uid) {
      uploadFileDoc(event)
    }
  })
}

const uploadFileDoc = (event) => {
  const file = event.file
  http({
    url: http.adornUrl('/admin/file/getPreSignUrl'),
    method: 'get',
    params: http.adornParams({
      fileName: file.name,
      isImFile: false
    })
  }).then(async ({ data }) => {
    await uploadFile(data.preSignUrl, event.file, (evt) => {
      progressFn(event.file, evt)
    }).then(() => {
      // 文件太小 秒传 来不及调用progressFn 直接 100%
      progressFn(event.file, { loaded: 1, total: 1 })
      dataForm.value.fileId = data.filePath
      onSave()
    })
  }).catch(() => {
    isSubmit.value = false
  })
}
const progressFn = (file, evt) => {
  docList.value.forEach(d => {
    if (d.uid === file.uid) {
      d.progress = parseInt(evt.loaded / evt.total * 100)
    }
  })
}

const onUploadChange = (file, fileList) => {
  const isLtSize = file.size / 1024 / 1024 < 2
  if (!isLtSize) {
    ElMessage.error('上传文件大小不能超过2MB')
    uploadRef.value?.handleRemove(file)
    return
  }
  const isPdf = [
    'application/pdf'
  ]
  if (isPdf.indexOf(file.raw.type) === -1) {
    ElMessage.error('请上传PDF格式的发票')
    uploadRef.value?.handleRemove(file)
    return false
  }
  if (isSubmit.value) {
    return
  }
  const videoSrc = URL.createObjectURL(file.raw)
  docList.value.push({ url: videoSrc, uid: file.uid, name: file.name })
  dataForm.value.fileId = !!docList.value.length
  dataFormRef.value?.validateField('fileId')
}

const preDeleteVideo = (index) => {
  docList.value.splice(index, 1)
  dataForm.value.fileId = ''
}

const onDownload = () => {
  http({
    url: http.adornUrl(`/orderInvoice/download/${orderNumber.value}`),
    method: 'put',
    data: http.adornData({}),
    responseType: 'blob' // 解决文件下载乱码问题
  }).then(({ data }) => {
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = `物料清单-${orderNumber.value}.xlsx`
    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  }).catch((e) => {
    ElMessage.error(e)
  })
}

</script>

<style lang="scss" scoped>
.inv-item{
  .copy{
    display: none;
    margin-left: 10px;
  }

  &:hover{
    .copy{
      display: inline-block;
    }
  }
}

.upload-video-box {
  width: 100%;

  .video-preview {
    width: 128px;
    height: 128px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    cursor: pointer;
    box-sizing: border-box;
    margin-right: 8px;
    margin-bottom: 5px;
    position: relative;
    overflow: hidden;

    &:hover{
      .el-icon-delete {
        display: block;
      }
    }

    .el-icon-delete{
      display: none;
      background: rgba(0, 0, 0, .3);
      height: 30px;
      width: 100%;
      text-align: center;
      padding: 5px;
      position: absolute;
      bottom: 0;
      left: 0;
      font-size: 20px;
    }

    .progress{
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 128px;
      padding: 24px;
      background: rgba(0, 0, 0, .5);

      :deep(.el-progress__text){
        color: #fff;
      }
    }
  }
}
</style>
